<?php
/**
 * Administracja - importowanie danych z pliku
 * @author Miron Pawlik
 */

if(is_uploaded_file($_FILES['import']['tmp_name']))
{
	
	$choose = file($_FILES['import']['tmp_name']);
	$studentID = 0;
	$terms = array();
	foreach($choose as $line => $cho)
	{
		$cho = trim($cho);
		if($cho == "") continue;
		if(ereg("^\[([0-9]{1,6})\]$", $cho, $reg))
		{
			$terms[$reg[1]] = array();
			$studentID = $reg[1];
		}
		//@TODO poprawic regexpy dla numerów
		elseif(ereg('^([0-9]{1,3}):([0-9]{1,5})$', $cho, $reg) && is_array( $terms[$studentID] ))
		{
			$terms[$studentID][$reg[1]] = $reg[2];
		}
		else
		{
			$errorMsg = "Bład w linijce ".($line+1)." (".$cho.")";
			break;
		}
	}
	if(!$errorMsg)
	{
		set_time_limit(120);
		$db->addNew('schedules', array('name' => $fd['name'], 'upload' => time()));
                $id = $db->LastId('schedules', 'scheduleID');
		foreach($terms as $stud => $term)
		{
			foreach($term as $sub => $t)
			{
				$db->addNew('chosenTerms', array('indexID'=>$stud, 'subjectID'=>$sub, 'termID'=>$t, 'scheduleID' => $id));
			}
		}
	}
	$smarty->assign('import', $fd['import']);
}
elseif($fd[2] == 'del' && is_numeric($fd[3]))
{
    $db->delById($fd[3], 'schedules', 'scheduleID');
    $db->deleteAll('chosenTerms', 'scheduleID = '.$fd[3]);
    header("Location: ".$_conf['host'].'?admin,import');
}


$schedules = $db->getAll('schedules');
$smarty->assign('schedules', $schedules);
